package com.wideplay.crosstalk;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.wideplay.warp.persist.PersistenceService;
import com.wideplay.warp.widgets.WidgetFilter;
import org.hibernate.SessionFactory;

import javax.servlet.*;
import java.io.IOException;

import net.jcip.annotations.Immutable;

/**
 * A wrapper for warp-widgets filter which lets us hook into the servlet lifecycle
 * to start and stop our (rather expensive) persistence services.
 *
 * @author Dhanji R. Prasanna (dhanji@gmail.com)
 */
@Immutable @Singleton
class CrosstalkLifecycleFilter implements Filter {
    private final WidgetFilter widgetFilter;
    private final PersistenceService persistence;
    private final Provider<SessionFactory> sessionFactory;

    @Inject
    public CrosstalkLifecycleFilter(WidgetFilter widgetFilter, PersistenceService persistence,
                                    Provider<SessionFactory> sessionFactory) {

        this.widgetFilter = widgetFilter;
        this.persistence = persistence;
        this.sessionFactory = sessionFactory;
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        widgetFilter.init(filterConfig);

        //start up warp-persist
        persistence.start();
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        widgetFilter.doFilter(servletRequest, servletResponse, filterChain);
    }

    public void destroy() {
        try {
            //close down Hibernate via a provider pattern
            sessionFactory.get().close();

        } finally {
            //we use a finally in case an exception is thrown in closing hibernate down
            widgetFilter.destroy();
        }
    }
}
